package com.test.spring.fusion.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.test.spring.fusion.utlis.DateUtil;

@RestController
public class MongodbController {
	

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@GetMapping("find")
	public Object find() {
		Criteria criteria = Criteria.where("id").exists(true);
//		Pattern pattern = Pattern.compile("^.*17.*$", Pattern.CASE_INSENSITIVE);
//		criteria.and("time").regex(pattern);
		Query query = Query.query(criteria);
		query.with(Sort.by(Sort.Order.asc("id")));
		query.fields().include("id");
		query.fields().include("time");
		return mongoTemplate.find(query, JSONObject.class,"zhaoyan");
	}
	
	@GetMapping("save")
	public String save() {
		String classStr = "{'classId':'1','abc':'12345'}";
		JSONObject parseObject = JSON.parseObject(classStr);
		parseObject.put("time", "2019-09-17");
		Object insert = mongoTemplate.insert(parseObject,"zhaoyan");
		System.out.println(insert);
		
//		Query query = Query.query(Criteria.where("abc").is("12345"));
//		query.skip(3).limit(2);
//		List<JSONObject> find = mongoTemplate.find(query, JSONObject.class,"zhaoyan");
//		if(find!=null && find.size()>0) {
//			for (JSONObject object : find) {
//				System.out.println(object);
//			}
//		}
//		JSONObject findById = mongoTemplate.findById("cd431bab-5db7-4bbb-ad5e-657e6d32e98e", JSONObject.class,"zhaoyan");
//		System.out.println(findById);
		return UUID.randomUUID().toString();
	}
	
	@GetMapping("a")
	@SuppressWarnings("all")
	public Map<String, Object> findStatisticalByTimeDay() {
		String name="humity";
	    int dayNum =30;
	    String codeId="37234d9a-0689-49d7-a6d9-41d873b7b134";
		Map<String, Object> hashMap = new HashMap<>();
		List<Object> valuesList = new ArrayList<>();
		// x轴的时间
		String[] beforeDay = DateUtil.getBeforeDay(dayNum);
		// 取值范围最小值
		Date minStringDate = DateUtil.minStringDate(beforeDay[0]);
		// 取值范围最大值
		Date maxStringDate = DateUtil.maxStringDate(beforeDay[beforeDay.length - 1]);
		Aggregation aggregation4 = Aggregation.newAggregation(
				Aggregation.match(Criteria.where("deviceId").ne(codeId)),
				Aggregation.match(Criteria.where("timeDate").gte(minStringDate)),
				Aggregation.match(Criteria.where("timeDate").lte(maxStringDate)),
				Aggregation.match(Criteria.where(name).exists(true)),
				Aggregation.project(name).andExpression("{$dateToString:{format:'%Y-%m-%d',date: {$add:{'$timeDate',8*60*60000}}}}").as("timeDate"),
				Aggregation.group("timeDate").avg(name).as("avg"));
		String startTime = new Date().toLocaleString();
		System.out.println(startTime);
		AggregationResults<Map> aggregationResults = mongoTemplate.aggregate(aggregation4, "zhaoyan",Map.class);
		String endTime = new Date().toLocaleString();
		System.out.println(endTime);
		Map<String, Object> mapValue = new HashMap<>();
		if (aggregationResults != null) {
			List<Map> mappedResults = aggregationResults.getMappedResults();
			if (mappedResults != null && mappedResults.size() > 0) {
				for (Map map : mappedResults) {
					String valueOf = String.valueOf(map.get("_id"));
					Object object = map.get("avg");
					BigDecimal bg = new BigDecimal(String.valueOf(object));
					double bgValue = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					mapValue.put(valueOf, bgValue);
				}
			}
		}
		for (String dayKey : beforeDay) {
			Object object = mapValue.get(dayKey);
			valuesList.add(object=object!=null? object : 0);
		}
		hashMap.put("start", startTime);
		hashMap.put("endtt", endTime);
//		hashMap.put("x", beforeDay);
//		hashMap.put("v", valuesList);
		return hashMap;
	}

}
